import ctypes
import os
import sys
import threading

from PyQt5.QtCore import Qt
from PyQt5.QtGui import QPixmap, QImage, QIcon
from PyQt5.QtWidgets import QMainWindow, QStatusBar, QTableWidget, QTextBrowser, QLabel, QPushButton, QVBoxLayout, \
    QHBoxLayout, QWidget, QTableWidgetItem, QApplication, QMessageBox, QAbstractItemView
from PyQt5 import QtCore

from Function import rows, Number_Of_Picture

from Iserve import MyServer_start, MyServer
from delete_window import delete_window
from inquire_window import inquire_window
from insert_window import insert_window
from modify_window import modify_window

import Ico

path_of_folder = ''
number_of_picture = 0
now_picture = 0

# class Ui_MainWindow(QWidget) :
class Ui_MainWindow(QMainWindow) :
    def __init__(self):
        super(Ui_MainWindow,self).__init__()
        self.initUI()
        # 宽度 高度
        self.resize(720, 500)
        # self.addAction(self.statusBar)
        self.statusBar = QStatusBar()
        self.setStatusBar(self.statusBar)

    def initUI(self):
        self.setWindowTitle("管理系统")
        self.setWindowIcon(QIcon(':/Ico.ico'))
        # 表格
        self.tablewidget = QTableWidget()
        self.tablewidget.setRowCount(1)
        self.tablewidget.setColumnCount(6)
        # 设置列名
        self.tablewidget.setHorizontalHeaderLabels(["车牌号","时间", "姓名", "手机号", "是否处理","图片"])
        # self.tablewidget.setEditTriggers(QAbstractItemView.NoEditTriggers)

        # 提示区
        self.textbrowser = QTextBrowser()
        self.textbrowser.setMaximumHeight(100)

        # 提示区标签
        self.label3 = QLabel()
        self.label3.setText("状态区")
        self.label3.setStyleSheet("QLabel{color:rgb(0,0,0);font-size:20px;font-weight:normal;font-family:Arial;font-weight:bold;}")

        # 查询图片
        # filename1 = r'D:\1.jpg'
        # img1 = QImage(filename1)
        self.label1 = QLabel()
        self.label1.setFixedWidth(200)
        self.label1.setFixedHeight(150)
        # result1 = img1.scaled(self.label1.width(), self.label1.height(), Qt.IgnoreAspectRatio, Qt.SmoothTransformation)
        # self.label1.setPixmap(QPixmap(result1))
        self.label1.setText('暂无图片')

        # 循环图片
        # filename2 = r'D:\1.jpg'
        # img2 = QImage(filename2)
        self.label2 = QLabel()
        self.label2.setFixedWidth(200)
        self.label2.setFixedHeight(150)
        # result2 = img2.scaled(self.label2.width(), self.label2.height(), Qt.IgnoreAspectRatio, Qt.SmoothTransformation)
        # self.label2.setPixmap(QPixmap(result2))
        self.label2.setText('暂无图片')

        # 按键
        self.button_read = QPushButton("读取")
        self.button_insert = QPushButton("插入")
        self.button_delete = QPushButton("删除")
        self.button_inquire = QPushButton("查询")
        self.button_modify = QPushButton("修改")
        self.button_restart = QPushButton("重启")

        # 定义布局
        vbox11 = QVBoxLayout()
        hbox12 = QHBoxLayout()
        vbox13 = QVBoxLayout()
        vbox14 = QVBoxLayout()
        hbox15 = QHBoxLayout()

        # 表格 状态提示 提示区
        vbox11.addWidget(self.tablewidget)
        vbox11.addWidget(self.label3)
        vbox11.addWidget(self.textbrowser)

        # 图片
        hbox12.addWidget(self.label1)
        hbox12.addWidget(self.label2)

        # 按键
        vbox14.addWidget(self.button_read)
        vbox14.addWidget(self.button_insert)
        vbox14.addWidget(self.button_delete)
        vbox14.addWidget(self.button_inquire)
        vbox14.addWidget(self.button_modify)
        vbox14.addWidget(self.button_restart)

        # 添加表格和图片
        vbox13.addLayout(vbox11)
        vbox13.addLayout(hbox12)

        # 添加表格、图片、按钮
        hbox15.addLayout(vbox13)
        hbox15.addLayout(vbox14)

        # 定时更新图片
        timer = QtCore.QTimer(self)
        timer.timeout.connect(self.update_image)
        timer.start(10 * 1000)

        # 信号与槽连接
        self.button_read.clicked.connect(self.read)
        self.button_insert.clicked.connect(self.insert)
        self.button_delete.clicked.connect(self.delete)
        self.button_inquire.clicked.connect(self.inquire)
        self.button_modify.clicked.connect(self.modify)
        self.button_restart.clicked.connect(self.restart)

        # 添加布局
        widget = QWidget()
        widget.setLayout(hbox15)
        self.setCentralWidget(widget)
        self.resize(720, 300)

        #开启TCP服务
        self.start()
    def start(self):
        self._thread = MyServer_start()
        self._thread.start()
        self._thread.tcp_signal.connect(self.restart_state)

    def read(self):
        t = threading.Thread(target=self.read_handle)
        t.start()  # 告诉操作系统开一个线程

    def read_handle(self):
        # 获取行数与内容
        i, data= rows(self)
        print("数据库中的行数：", i)
        self.tablewidget.setRowCount(i)
        # 打印测试
        print("数据库中数据", data)

        # 遍历二维元组, 将 id 和 name 显示到界面表格上
        x = 0
        for i in data:
            y = 0
            for j in i:
                self.tablewidget.setItem(x, y, QTableWidgetItem(str(data[x][y])))
                y = y + 1
            x = x + 1
        self.statusBar.showMessage("读取成功！", 3000)
        self.textbrowser.append("读取成功!")

    def insert(self):
        try:
            dialog = insert_window(self)
            dialog.Signal_TwoParameter.connect(self.deal_state_emit_slot)
            dialog.show()
        except Exception as e:
            print(e)
            QMessageBox.critical(self, '错误', '未知错误', QMessageBox.Yes)

    def delete(self):
        try:
            dialog = delete_window(self)
            dialog.Signal_TwoParameter.connect(self.deal_state_emit_slot)
            dialog.show()
        except Exception as e:
            print(e)
            QMessageBox.critical(self, '错误', '未知错误', QMessageBox.Yes)

    def inquire(self):

        dialog = inquire_window(self)
        # 连接子窗口的自定义信号与主窗口的槽函数
        dialog.Signal_OneParameter.connect(self.deal_inquire_emit_slot)
        dialog.Signal_TwoParameter.connect(self.deal_state_emit_slot)

        dialog.show()

    def deal_inquire_emit_slot(self,data):
        len_data = len(data)
        if len(data) == 0:
            QMessageBox.critical(self, '错误', '数据库中无该数据，请核对输入的数据是否有误！', QMessageBox.Yes)
        else:
            self.tablewidget.setRowCount(len_data)
        try:
            x = 0
            for i in data:
                y = 0
                for j in i:
                    self.tablewidget.setItem(x, y, QTableWidgetItem(str(data[x][y])))
                    y = y + 1
                x = x + 1

                File_Path = str(data[0][5])
                print(File_Path)
                if not os.path.exists(File_Path):
                    self.label1.setText("暂无图片")
                    return
                img1 = QImage(File_Path)

                result = img1.scaled(self.label1.width(), self.label1.height(), Qt.IgnoreAspectRatio,
                                      Qt.SmoothTransformation)
                self.label1.setPixmap(QPixmap(result))
            print("查询成功")
        except Exception as e:
            print(e)
            QMessageBox.critical(self, '错误', '未知错误', QMessageBox.Yes)
    def modify(self):
        try:
            dialog = modify_window(self)
            dialog.Signal_TwoParameter.connect(self.deal_state_emit_slot)
            dialog.show()
        except Exception as e:
            print(e)
            QMessageBox.critical(self, '错误', '未知错误', QMessageBox.Yes)
    def restart_state(self, state, Tip):
        if state == '开启成功':
            # t = threading.Thread(target=self.restart_handle)
            # t.start()  # 告诉操作系统开一个线程
            self.statusBar.showMessage("开启成功！", 3000)
            self.textbrowser.append("开启成功!")
            self.textbrowser.append(Tip)
        print(state)
        if state == '1':
            self.textbrowser.append("重启失败!")
            self.statusBar.showMessage("重启失败！", 3000)

    def update_image(self):
        global number_of_picture
        global now_picture
        number_of_picture = int(Number_Of_Picture()[0])
        path_of_folder = str(Number_Of_Picture()[1])

        if number_of_picture == 0 :
            self.label2.setText("暂无图片")
            return

        if now_picture < number_of_picture:
            now_picture += 1
        else:
            number_of_picture = Number_Of_Picture()[1]
            now_picture = 1

        path_of_image = path_of_folder + "/" + str(now_picture) + ".jpg"
        img = QImage(path_of_image)
        result = img.scaled(self.label1.width(), self.label1.height(), Qt.IgnoreAspectRatio,
                             Qt.SmoothTransformation)
        self.label2.setPixmap(QPixmap(result))

    def restart(self):
        ret = ctypes.windll.kernel32.TerminateThread(  # @UndefinedVariable
            self._thread.handle, 0)

        print('终止线程', self._thread.handle, ret)
        # if self._thread.isRunning():
        #     self._thread.quit()
        #     # 强制
        #     # self._thread.terminate()
        # del self._thread
        self.start()

    def deal_state_emit_slot(self, value):
        if value == 'insert_window_succeed':
            self.statusBar.showMessage("插入成功！", 3000)
            self.textbrowser.append("插入成功!")
        if value == 'insert_window_fail':
            self.statusBar.showMessage("插入失败！", 3000)
            self.textbrowser.append("插入失败!")

        if value == 'delete_window_succeed':
            self.statusBar.showMessage("删除成功", 3000)
            self.textbrowser.append("删除成功!")
        if value == 'delete_window_fail':
            self.statusBar.showMessage("删除失败", 3000)
            self.textbrowser.append("删除失败!")

        if value == 'inquire_window_succeed':
            self.statusBar.showMessage("查询成功！", 3000)
            self.textbrowser.append("查询成功!")
        if value == 'inquire_window_fail':
            self.statusBar.showMessage("查询失败！", 3000)
            self.textbrowser.append("查询失败!")

        if value == 'modify_window_succeed':
            self.statusBar.showMessage("修改成功！", 3000)
            self.textbrowser.append("修改成功!")
        if value == 'modify_window__fail':
            self.statusBar.showMessage("修改失败！", 3000)
            self.textbrowser.append("修改失败!")

    def tcp_handle(self, data):
        self.statusBar.showMessage(data, 3000)
        self.textbrowser.append(data)







if __name__ == '__main__':
    # 主线程销毁, 子线程销毁
    # 或
    # t = threading.Thread(target=MyServer_start)
    # t.setDaemon(True)
    # t.start()  # 告诉操作系统开一个线程
    # t.join() # 等待进程完成
    # t = threading.Thread(target=MyServer_start, daemon=True)
    # t.start()  # 告诉操作系统开一个线程
    app = QApplication(sys.argv)
    app.setWindowIcon(QIcon('Ico/Ico.ico'))
    main = Ui_MainWindow()
    main.show()

    sys.exit(app.exec_())